<template>
  <ul class="select-users--tree">
    <li v-for="dept in list" :key="dept.deptId">
      <div class="">
        <el-checkbox v-if="multiple" :value="isSelectedDept(dept)" @change="val => selectDept(val, dept)">
          {{ dept.name }}
        </el-checkbox>
        <span v-else>
          {{ dept.name }}
        </span>
      </div>

      <!-- 用户选择 -->
      <ul v-if="dept.users && dept.users.length > 0" class="select-users--tree__users">
        <li v-for="user in dept.users" :key="user.userId">
          <el-checkbox :value="isSelected(user.userId)" @change="val => selectItem(user)">
            {{ user.username }}
          </el-checkbox>
        </li>
      </ul>

       <!-- 子部门递归 -->
      <tree
        v-if="dept.children && dept.children.length > 0"
        :value="value"
        :multiple="multiple"
        :list="dept.children"
        @input="handleInput"
      />
    </li>
  </ul>
</template>

<script>
import tree from "./index";

export default {
  name: "tree",

  components: {
    tree,
  },

  props: {
    value: {
      type: [Array, String, Number],
      default: null,
    },
    list: {
      type: Array,
      required: true,
    },
    multiple: {
      type: Boolean,
      default: false,
    },
  },

  methods: {
    // 获取当前部门下所有的用户id
    getAllUserIds(dept) {
      let userIds = dept.users && dept.users.map(user => user.userId) || [];

      if (dept.children && dept.children.length > 0) {
        userIds = dept.children.reduce((t, item) => {
          return [...t, ...this.getAllUserIds(item)]
        }, userIds)
      }

      return userIds;
    },
    selectDept(val, dept) {
      const users = this.getAllUserIds(dept);
      if (val) {
        this.$emit("input", [...this.value, ...users.filter(userId => !this.isSelected(userId))]);
      } else {
        this.$emit("input", this.value.filter(userId => !users.some(e => e === userId)));
      }
    },
    // 是否选择部门
    isSelectedDept(dept) {
      const users = this.getAllUserIds(dept);
      return users.length && users.every((userId) => this.isSelected(userId));
    },
    // 点击选择
    selectItem(user) {
      const isSelected = this.isSelected(user.userId);
      if (this.multiple) {
        if (isSelected) {
          this.handleInput(this.value.filter((u) => u !== user.userId));
        } else {
          this.handleInput([...this.value, user.userId]);
        }
      } else {
        if (isSelected) {
          this.handleInput('');
        } else {
          this.handleInput(user.userId);
        }
      }
    },
    // 是否选中
    isSelected(userId) {
      if (this.multiple) {
        return this.value.some(e => e === userId);
      }
      return this.value === userId;
    },
    handleInput(newValue) {
      this.$emit("input", newValue);
    },
  },
};
</script>

<style scoped>
.select-users--tree {
  list-style-type: none;
  padding-left: 20px;
}
.select-users--tree__users {
  padding-left: 20px;
}
</style>